//
//  YLAlert.swift
//  QingLiuSwift
//
//  Created by xyanl on 2023/12/11.
//

import UIKit
import Foundation
import Localize_Swift

class YLAlert: NSObject {
    
//    private var controller: UIViewController!
//    private var style: UIAlertController.Style = .alert
//    private var title: String?
//    private var message: String?
//    private var actionTitles: Array<String>
//    private var cancelTitle: String?
//    private var cancelStyle: UIAlertAction.Style = .cancel
//    private var selectedHandler: ((UIAlertAction, Int) -> Void)?
//    private var cancelHandler: ((UIAlertAction) -> Void)?
    
    @discardableResult
    init(
        controller: UIViewController,
        style: UIAlertController.Style = .alert,
        title: String? = nil,
        message: String? = nil,
        actionTitles: Array<String>,
        cancelTitle: String? = "取消",
        cancelStyle: UIAlertAction.Style = .cancel,
        selectedHandler: ((UIAlertAction, Int) -> Void)? = nil,
        cancelHandler: ((UIAlertAction) -> Void)? = nil
    ) {
//        self.controller = controller
//        self.style = style
//        self.title = title
//        self.message = message
//        self.actionTitles = actionTitles
//        self.cancelTitle = cancelTitle
//        self.cancelStyle = cancelStyle
//        self.selectedHandler = selectedHandler
//        self.cancelHandler = cancelHandler
        super.init()
        
        YLAlert.alert(controller: controller, style: style, title: title, message: message, actionTitles: actionTitles, cancelTitle: cancelTitle, cancelStyle: cancelStyle, selectedHandler: selectedHandler, cancelHandler: cancelHandler)
    }
    
    static func alert(
        controller: UIViewController,
        style: UIAlertController.Style = .alert,
        title: String? = nil,
        message: String? = nil,
        actionTitles: Array<String>,
        cancelTitle: String? = "取消",
        cancelStyle: UIAlertAction.Style = .cancel,
        selectedHandler: ((UIAlertAction, Int) -> Void)? = nil,
        cancelHandler: ((UIAlertAction) -> Void)? = nil
    ) {
        let alerController = UIAlertController(title: title?.localized(), message: message?.localized(), preferredStyle: style)
        
        if cancelTitle != nil {
            let cancelAction = UIAlertAction(title: cancelTitle!.localized(), style: cancelStyle, handler: cancelHandler)
            alerController.addAction(cancelAction)
        }
        
        for (index, title) in actionTitles.enumerated() {
            let action = UIAlertAction(title: title.localized(), style: .default) { action in
                selectedHandler?(action, index)
            }
            alerController.addAction(action)
        }
        
        controller.present(alerController, animated: true)
    }
    
}
